package com.jack006.api.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Classname ServiceLogAspect
 * @Description 切面拦截
 * @Date 2021-06-14 17:03
 * @Created by jack
 */
@Aspect
@Component
public class ServiceLogAspect {

    final static Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    /**
     * AOP 通知
     * 1、前置通知
     * 2、后置通知
     * 3、环绕通知
     * 4、异常通知
     * 5、最终通知
     *
     * 使用环绕通知
     * * 拦截所有返回的类型
     * com.jack006.*.service.impl..  匹配当前包和包下面的子包
     * *.* 匹配到某个类，当前类的方法
     * (..)任意参数
     */
    @Around("execution(* com.jack006.*.service.impl..*.*(..))")
    public Object recordTimeOfService(ProceedingJoinPoint joinPoint)
            throws Throwable {
        logger.info("====== 开始执行 {}.{} ===",
                joinPoint.getTarget().getClass(),
                joinPoint.getSignature().getName());

        long startTime = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis();
        long taskTime = endTime - startTime;

        if (taskTime > 3000) {
            logger.error("当前执行耗时 ms：{}",taskTime);
        } else if (taskTime > 2000){
            logger.warn("当前执行耗时 ms ：{}",taskTime);
        } else {
            logger.info("当前执行耗时 ms ：{}",taskTime);
        }

        return result;
    }
}
